package cn.momoky.ccool.controller;

import cn.momoky.ccool.pojo.FileNode;
import cn.momoky.ccool.service.FileNodeService;
import cn.momoky.ccool.service.FileService;
import cn.momoky.ccool.utils.WebUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping("/img")
@AllArgsConstructor
public class ImageController {

    FileService fileService;
    FileNodeService fileNodeService;

    @GetMapping("/id/{id}/w/{width}")
    public void size(@PathVariable("id") Long id, @PathVariable("width") Integer width) throws IOException {
        FileNode fn = fileNodeService.findById(id);

        if (!fn.getIsDir() && !fn.getType().startsWith("image/")) return;

        FileInputStream in = fileService.getFileInputStream(id);

        if (in == null) return;

        BufferedImage image = ImageIO.read(in);

        int w = image.getWidth();
        double f = (width*1.0)/w;
        int height = (int)(f * image.getHeight());

        HttpServletResponse resp = WebUtils.getResponse();
        resp.setHeader("Content-Disposition",
                "attachment;fileName=" + fn.getName() + "");
        resp.setContentType(fn.getType());

        Thumbnails.of(image)
                .outputQuality(1)
                .size(width, height)
                .outputFormat(fn.getType().split("/")[1])
                .toOutputStream(resp.getOutputStream());

    }
}
